import React, { useState, useEffect } from "react";
import {
  List,
  ListItem,
  ListItemText,
  CircularProgress,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  ThemeProvider,
  createTheme,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { getCrmMailmergeList } from "../../util/util";

// 通用打印预览
const Mailmergeshow = (pagedata) => {
  const [loading, setLoading] = useState(true);
  const [selectedRow, setSelectedRow] = useState(null);
  const [groupedTemplates, setGroupedTemplates] = useState({});

  let Entityname = pagedata?.data?.Entity;
  let dataid = pagedata?.data?.EntityId[0];

  useEffect(() => {
    // console.log('pagedata', pagedata);
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await getCrmMailmergeList(Entityname);
        // console.log("response", response);
        if (
          response &&
          response.details &&
          response.details.statusMessage &&
          response.details.statusMessage.templates
        ) {
          const templatesArray = response.details.statusMessage.templates
            .filter((item) => item.folder.name !== "停用")
            .map((item) => ({
              ...item,
              filename: item.name.replace(/\.zdoc$/, ""),
            }));
          // console.log("templatesArray", templatesArray);

          const tempGroupedTemplates = templatesArray.reduce((acc, item) => {
            const folderName = item.folder.name;
            if (!acc[folderName]) {
              acc[folderName] = [];
            }
            acc[folderName].push(item);
            return acc;
          }, {});

          setGroupedTemplates(tempGroupedTemplates);
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        setLoading(false);
      }
    };

    const initialize = async () => {
      await window.zohoReadyPromise;
      // console.log("ZOHO is ready", window.ZOHO); // ZOHO is ready
      fetchData();
    };
    initialize();
  }, [pagedata, Entityname, dataid]);

  const handleClick = async (record) => {
    setLoading(true);
    try {
      const filename = `${record.filename}${dataid}.pdf`;
      const req_data = {
        arguments: JSON.stringify({
          entityname: Entityname,
          dataid: dataid,
          templateid: record.id,
          filename: filename,
        }),
      };

      const filedata = await window.ZOHO.CRM.FUNCTIONS.execute(
        "print_bs",
        req_data
      );

      if (filedata && filedata.details && filedata.details.output) {
        const strdata = filedata.details.output;
        const byteCharacters = atob(strdata);
        const byteArrays = [];
        for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
          const slice = byteCharacters.slice(offset, offset + 1024);
          const byteNumbers = new Array(slice.length);
          for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
          }
          byteArrays.push(new Uint8Array(byteNumbers));
        }

        const blob = new Blob(byteArrays, { type: "application/pdf" });
        const blobURL = URL.createObjectURL(blob);
        window.open(blobURL, "_blank");
      }
    } catch (error) {
      console.error("Error fetching PDF:", error);
    } finally {
      setLoading(false);
    }
  };

  // 自定义主题
  const theme = createTheme({
    components: {
      MuiAccordion: {
        styleOverrides: {
          root: {
            '&.Mui-expanded': {
              margin: 0,
            },
          },
        },
      },
    },
  });

  return (
    <ThemeProvider theme={theme}>
      <div style={{ position: "relative", minHeight: "95vh" }}>
        {loading ? (
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              height: "95vh",
            }}
          >
            <CircularProgress />
          </div>
        ) : (
          Object.keys(groupedTemplates).map((folderName, index) => (
            <Accordion 
            key={index} 
            defaultExpanded={index === 0}>
              <AccordionSummary 
              expandIcon={<ExpandMoreIcon />}>
                {folderName}
              </AccordionSummary>
              <AccordionDetails>
                <List>
                  {groupedTemplates[folderName].map((item) => (
                    <ListItem
                      key={item.id}
                      button={"true"}
                      onClick={() => handleClick(item)}
                      onMouseEnter={() => setSelectedRow(item.id)}
                      onMouseLeave={() => setSelectedRow(null)}
                      style={{
                        padding: "2px 2px 2px 2px",
                        backgroundColor:
                          item.id === selectedRow ? "#e6f7ff" : "transparent", cursor: "pointer",
                      }}
                    >
                      <ListItemText primary={item.filename} />
                    </ListItem>
                  ))}
                </List>
              </AccordionDetails>
            </Accordion>
          ))
        )}
      </div>
    </ThemeProvider>
  );
};

export default Mailmergeshow;
